import logging
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

from selenium.webdriver.chrome.service import Service



class TestCRUDApp(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        """初始化浏览器并打开应用"""
        cls.driver = webdriver.Chrome(service=Service('chromedriver.exe'))
        cls.driver.get("http://127.0.0.1:8001")
        cls.driver.maximize_window()
        logging.info("浏览器启动成功")

    @classmethod
    def tearDownClass(cls):
        """关闭浏览器"""
        cls.driver.quit()

    def test_1_add_user(self):
        """测试新增用户功能"""
        driver = self.driver

        driver.get("http://127.0.0.1:8001/")

        # 清除可能存在的搜索关键字
        try:
            search_input = driver.find_element(By.NAME, "keyword")
            search_input.clear()
        except:
            pass

        # 点击“新增”按钮
        add_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.LINK_TEXT, "新增"))
        )
        add_button.click()

        print("当前页面URL:", driver.current_url)
        print("当前页面标题:", driver.title)

        # 填写表单
        name_input = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.NAME, "name"))
        )
        name_input.send_keys("Test User")

        age_input = driver.find_element(By.NAME, "age")
        age_input.send_keys("30")

        gender_radio = driver.find_element(By.XPATH, "//input[@value='男']")
        gender_radio.click()

        phone_input = driver.find_element(By.NAME, "phone")
        phone_input.send_keys("1234567890")

        # 提交表单（更换为更稳定的方式）
        submit_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//button[contains(., '保存')]"))
        )
        submit_button.click()

        # 验证 success-message 是否出现
        success_message = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.ID, "success-message"))
        )
        self.assertIn("added", success_message.text.lower())


    def test_2_edit_user(self):
        """测试编辑第一个用户的功能"""
        driver = self.driver

        driver.get("http://127.0.0.1:8001/")

        # 点击第一个用户的“编辑”按钮
        edit_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "(//a[contains(text(), '编辑')])[1]"))
        )
        edit_button.click()

        # 修改姓名字段
        name_input = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.NAME, "name"))
        )
        name_input.clear()
        name_input.send_keys("Updated Name")

        # 提交修改
        submit_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), '保存')]"))
        )
        submit_button.click()

        # 等待跳转回首页
        WebDriverWait(driver, 10).until(
            EC.url_contains("success")
        )

        # 验证是否出现成功提示框
        success_message = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.ID, "success-message"))
        )
        self.assertIn("updated", success_message.text.lower())  # 更宽松的判断方式

    def test_3_search_user(self):
        """测试查询用户功能"""
        driver = self.driver

        driver.get("http://127.0.0.1:8001/")

        # 输入搜索关键字
        search_input = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.NAME, "keyword"))
        )
        search_input.clear()
        search_input.send_keys("Updated Name")

        current_url = driver.current_url

        # 点击查询按钮
        search_button = driver.find_element(By.ID, "button-addon1")
        search_button.click()

        # 等待 URL 变化（避免缓存）
        WebDriverWait(driver, 10).until(
            EC.url_changes(current_url)
        )

        # 验证搜索结果表格加载完成
        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.XPATH, "//table//tbody/tr"))
            )
            print("搜索结果成功")

            # 验证是否有匹配的数据行
            table_rows = driver.find_elements(By.XPATH, "//table//tbody/tr")
            if len(table_rows) > 0:
                print(f"检测到 {len(table_rows)} 条与 'Updated Name' 匹配的用户记录")
            else:
                print("未找到与关键词匹配的用户记录")

        except:
            self.fail("搜索结果表格加载失败")

    def test_4_delete_user(self):
        """测试删除用户的功能"""
        driver = self.driver

        driver.get("http://127.0.0.1:8001/")

        # 获取当前用户数
        initial_users = driver.find_elements(By.XPATH, "//table//tbody/tr")

        # 点击第一个用户的“删除”按钮
        delete_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "(//a[contains(text(),'删除')])[1]"))
        )
        delete_button.click()

        # 处理弹窗确认
        alert = WebDriverWait(driver, 10).until(EC.alert_is_present())
        alert.accept()

        # 验证用户数量减少
        WebDriverWait(driver, 10).until(
            lambda d: len(d.find_elements(By.XPATH, "//table//tbody/tr")) < len(initial_users)
        )

        # 验证是否出现成功提示框
        success_message = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.ID, "success-message"))
        )
        self.assertIn("deleted", success_message.text.lower())


if __name__ == "__main__":
    unittest.main()